<!-- 角色权限 -->
<style>
  table,
  thead,
  tbody,
  tr,
  td {
    border-bottom: 1px solid #ccc;
  }
  table {
    margin-top: 10px;
    width: 100%;
    border-collapse: collapse;
    text-align: center;
    line-height: 30px;
  }
  .user-btn_one {
    margin-top: 0px;
  }
  .user-two,
  .user-three,
  .user-four
   {
    width: 200px;
    height: 35px;
    border: 1px solid #606266;
    border-radius: 5px;
    margin-left: 20px;
  }
  .user-ipt{
    background-color: white;
    font-family: 20px;
    margin-left: 20px;
  }
  .user-modal{
    display: inline;
  }
  .modal-body input {
    display: inline;
  }
</style>
<div class="container-fluid">
  <div class="row">
    <!-- Button trigger modal -->
    <button
      type="button"
      class="btn btn-success user-btn_one"
      data-toggle="modal"
      data-target="#myModal"
    >
      添加
    </button>

    
    <input
      type="text"
      class="user-two"
      id="exampleInputName2"
      placeholder="请输入用户姓名"
    />
    <select class="user-two">
      <option class="user-val">请选择角色</option>
    </select>
    <input class="user-ipt" type="submit" value="搜索" style="border: none;" />
  </div>

  <div class="row">
    <div class="user-tables">
      <table>
        <thead>
          <tr>
            <td>序号</td>
            <td>用户名</td>
            <td>姓名</td>
            <td>角色</td>
            <td>性别</td>
            <td>状态</td>
            <td>手机号</td>
            <td>操作</td>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>
  </div>

  <div class="row">
    <nav aria-label="Page navigation">
      <ul class="pagination">
        <li class="num">
          <a href="#" aria-label="Previous">
            <span aria-hidden="true">&laquo;</span>
          </a>
        </li>
        <!-- <li><a href="#">1</a></li>
        <li><a href="#">2</a></li>
        <li><a href="#">3</a></li>
        <li><a href="#">4</a></li>
        <li><a href="#">5</a></li> -->
        <li>
          <a href="#" aria-label="Next">
            <span aria-hidden="true">&raquo;</span>
          </a>
        </li>
      </ul>
    </nav>
  </div>

    <!-- Modal -->
    <div
      class="modal fade"
      id="myModal"
      tabindex="-1"
      role="dialog"
      aria-labelledby="myModalLabel"
    >
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
          </div>
          <div id="qwe" class="modal-body">
            <div class="form-group">
              用户名:<input
                class="form-control input-lg"
                type="text"
                name="username"
                placeholder="请输入用户名"
              />
            </div>
            <div class="form-group">
              姓名:<input
                class="form-control input-lg"
                type="text"
                name="realname"
                placeholder="请输入姓名"
              />
            </div>
            <div class="form-group">
              <form>
              密码:
              <input
                type="password"
                class="form-control"
                id="exampleInputPassword1"
                name="password"
                placeholder="请输入密码"
                autocomplete="off"
              />
              </form>
            </div>
            <div class="form-group">
              性别:<input type="radio" name="gender" value="male" />男
              <input type="radio" name="gender" value="female" />女
            </div>
            <div class="form-group">
              手机号：<input
                class="form-control input-lg"
                type="text"
                name="telephone"
                placeholder="请输入手机号"
              />
            </div>
            <div class="form-group">
              出生日期：<input
                class="form-control input-lg"
                type="text"
                name="birth"
                placeholder="请输入出生日期，该功能未实现"
                readonly
              />
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">
              取消
            </button>
            <button type="button" class="btn btn-primary btn-add" id="btn-change">确定</button>
          </div>
        </div>
      </div>
    </div>
    </div>

    <!-- 设置的模态框 -->
    <div id="setting-modal" class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">设置角色</h4>
      </div>
      <div class="modal-body">
        <br>
        <br>
        <div class="setting-modal_username"><strong>用户名：</strong></div>
        <br>
        <br>
        <br>
        <div>
          <strong>角色：</strong>
          <select class="user-four">
          <option class="user-four_val" value="0">请选择角色</option>
          <option class="user-four_val" value="1">教师</option>
          <option class="user-four_val" value="6">学生</option>
          <option class="user-four_val" value="2">管理员</option>
          </select>
        </div>
        <br>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="setting-btn-primary">确定</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<script>
  var baseurl = "http://localhost:7788";
  var currentPage = 1;
  var pageSize = 10;
  var id;

// 全局设置token
// $.ajaxSetup({
//   headers:{
//     'Authorization':sessionStorage.getItem('token'),
//   }
// })

  function getData(type, url) {
    var p = new Promise((resole, reject) => {
      // 异步请求
      $.ajax({
        url: url,
        type: type,
        headers: {
          'Authorization': sessionStorage.getItem("token"),
        },
        success: function (data) {
          resole(data);
        },
      });
    });
    return p;
  }

  // 1.请求角色信息
  getData("get", baseurl + "/role/findAll").then(function (data) {
    console.log(data);
    data.data.forEach((item) => {
      // var num = Math.ceil(data.data.total / pageSize);
      // for (var i = num; i > 0; i++) {
      $(".container-fluid .user-val").after(
        `<option>` + item.name + `</option>`
      );
      // }
    });
  });

  // 封装请求用户函数-处理数据
  function getUserData(url) {
    // 2.请求用户所有信息
    return getData("get", baseurl + url).then(function (data) {
      // 先清空所有分页按钮
      if ($(".clicknum").length > 0) {
        $(".clicknum").remove();
      }
      // 获取用户总量，设置分页
      var num = Math.ceil(data.data.total / pageSize);
      for (var i = num; i > 0; i--) {
        $(".num").after(`<li class="clicknum"><a href="#">` + i + `</a></li>`);
      }
      // 给分页按钮绑定事件
      $(".clicknum").click(() => {
        currentPage = $(event.target).text();
        getUserData(
          "/baseUser/pageQuery?page=" + currentPage + "&pageSize=" + pageSize
        );
      });
      // 清空所有tobody元素
      $(".user-tables tbody").empty();
      // 获取用户信息追加到tr里面
      data.data.list.forEach((item) => {
        // console.log(item,"-=-=-=");
        $(".user-tables tbody").append(`
<tr>  
<td>${item.id}</td >
<td>${item.username}</td >
<td>${item.realname}</td >
<td>${item.roles
          .map(function (it) {
            return it.name;
          })
          .join()}</td >
<td>${item.gender === "male" ? "男" : "女"}</td>
<td>${item.status}</td >
<td>${item.telephone}</td >
<td>
<button class="setting">设置</button>
<button class="deleteById">移除</button>
<button class="details">详情</button>
<button class="changeusers" data-toggle="modal" data-target="#myModal" data-item='${JSON.stringify(item)}'>修改</button>
</td>
</tr> 
`);
        allData = data.data.list;
      });

  // 设置按钮
      $(".setting").click(()=>{
        // 显示模态框
         $('#setting-modal').modal();
         // 清除角色内容
         $(".user-four_val2").remove();
        // 显示数据
        var id = $(event.target).parent().parent().children().eq(0).text();
        // console.log(id,"++++==");
        var editData = allData.filter((item)=>{
          if(item.id==id){
          console.log(item.roles,"---");
            // $("input[name=username]").val(item.username);
            $(".setting-modal_username span").empty();
            $(".setting-modal_username").append(`<span>`+item.username+`</span>`);
            $(".user-four").append(`<option class="user-four_val2" selected="selected" disabled>${item.roles.map(function(it){
              return it.name;}).join()}</option>`);
          }
        })

        // 获取角色信息
        // getData("get",baseurl + "/role/findAll").then(function(res){
        //   console.log(res);
        //     $(".user-four_val2").remove();
        //   res.data.forEach((item)=>{
        //     $(".user-four .user-four_val").after(`<option class="user-four_val2" value="`+item.id+`">`+item.name+`</option>`);           
        //   })
        // })

        // 设置任务权限
        $("#setting-btn-primary").click(()=>{
           var roles = $('.user-four option:selected').val();
           console.log(roles);
        $.ajax({
          url:baseurl + "/baseUser/setRoles",
          type:"post",
          headers:{
            "Authorization":sessionStorage.getItem('token'),
          },
          data:{
            id:id,
            roles:roles
          },
          success:function(data){
            console.log(data);
            $(".user-four_val2").empty();
            $("#setting-modal").modal('hide');
            // 页面刷新
            getUserData(
              "/baseUser/pageQuery?page=" +
                currentPage +
                "&pageSize=" +
                pageSize
            );
          }
        })
        })
       
     })

 // 删除按钮
      $(".deleteById").click(() => {
        var id = $(event.target).parent().parent().children().eq(0).text();
        getData("get", baseurl + "/baseUser/deleteById?id=" + id).then(
          function (data) {
            if (data.status == 200) {
              alert(data.message);
            }
            //页面刷新
            getUserData(
              "/baseUser/pageQuery?page=" +
                currentPage +
                "&pageSize=" +
                pageSize
            );
          }
        );
      });

      // 点击详情按钮，页面跳转，把单个信息追加到个人信息页面
      $(".details").click(() => {
        $(".content-main").load("./pages/user.html");
        var username = $(event.target).parent().parent().children().eq(1).text();
        var rolename = $(event.target).parent().parent().children().eq(3).text();
        // console.log(username,rolename,currentPage);
        getData("get",baseurl +"/baseUser/pageQuery?page=" +currentPage +"&pageSize=" +pageSize +"&username=" +username +"&rolename=" +rolename
        ).then(function (data) {
          // console.log(data);
          // 清除信息
        $(".information-user_one td").empty();
        // 显示信息
        console.log(allData);
          data.data.list.forEach((item) => {
            $(".information-user_one").append(
              `
          <tr>
      <td>`+item.username+`</td>
      </tr>
      <tr>
      <td>`+item.realname+`</td>
      </tr>
      <tr>
      <td>`+item.telephone+`</td>
      </tr>
      <tr>
      <td>${item.gender === "male" ? "男" : "女"}</td>
      </tr>
      <tr>
      <td>`+item.registerTime+`</td><br>
      </tr>
      <tr>
      <td>`+item.status+`</td><br>
      </tr>
    </tr>
        `);
            $(".picture").append(`<img src="`+item.userFace+`" alt="图片无法显示">`)
          });
        });
      });

      // 修改按钮,将数值传入到文本框中
      $(".changeusers").click(() => {
        // alert(1);
        // 修改模态框的头部标题
        $(".modal-title").text("修改当前信息");
        // 获取数据
        //  var user = $('.changeusers').attr('data-item');
        //  console.log(user);
        // user = JSON.parse(user);
        // $("input[name=username]").val(user.username);
        // $("input[name=realname]").val(user.realname);
        // $("input[name=password]").val(user.password);
        // $("input[type=radio][value="+user.gender+"]").prop("checked",true);
        // $("input[name=telephone]").val(user.telephone);
        // $("input[name=birth]").val(user.birth);

          // console.log(allData);
        id = $(event.target).parent().parent().children().eq(0).text();
        console.log(id);
         var editData = allData.filter(function(item){
          if(item.id==id){
             $("input[name=username]").val(item.username);
             $("input[name=realname]").val(item.realname);
             $("input[name=password]").val(item.password);
             $("input[type=radio][value="+item.gender+"]").prop("checked",true);
             $("input[name=telephone]").val(item.telephone);
             item.birth = new Date(item.birth).toLocaleDateString();
             $("input[name=birth]").val(item.birth);
          }
         })

         // 修改-更新数据
     
     $('#btn-change').click(()=>{
      // console.log('1234');
      // var user;
      var username = $('input[name=username]').val();
      var realname = $('input[name=realname]').val();
      var password = $('input[name=password]').val();
      var gender = $('input[type=radio]:checked').val();
      var telephone = $('input[name=telephone]').val();
      // var birth = $('input[name=birth]').val();
      console.log(username,realname);
        //   var save={
        //   id:id,
        //   username:username,
        //   realname:realname,
        //   password:password,
        //   gender:gender,
        //   telephone:telephone,
        //   // birth:birth,
        //   }

        // $.post(baseurl + '/baseUser/saveOrUpdate',save,function(res){
        //   // console.log(res,'----');
        //    $('#myModal').modal('hide');
        //    alert("修改成功！");
        //    getUserData(
        //    "/baseUser/pageQuery?page=" + currentPage + "&pageSize=" + pageSize
        //    );
        // })

         $.ajax({
             url:baseurl + '/baseUser/saveOrUpdate',
             type:"post",
             headers:{
            'Authorization':sessionStorage.getItem('token'),
              },
             data:{
                id:id,
                username:username,
                realname:realname,
                password:password,
                gender:gender,
                telephone:telephone,
                // birth:birth,
              },
              success:function(res){
                console.log(res);
                $('#myModal').modal('hide');
                alert("修改成功！");
                getUserData(
            "/baseUser/pageQuery?page=" + currentPage + "&pageSize=" + pageSize
          );
      }
    })
      })

      });

      
    });
  }

  getUserData(
    "/baseUser/pageQuery?page=" + currentPage + "&pageSize=" + pageSize
  );

  // 给搜索按钮绑定事件
  $(".user-ipt").click(() => {
    // 获取用户输入
    var username = $("input").val();
    var rolename = $("select").find("option:selected").val();
    console.log(username, rolename);
    if (username != "" && rolename == "请选择角色") {
      url =
        "/baseUser/pageQuery?page=" +
        currentPage +
        "&pageSize=" +
        pageSize +
        "&username=" +
        username;
    } else if (username == "" && rolename != "请选择角色") {
      url =
        "/baseUser/pageQuery?page=" +
        currentPage +
        "&pageSize=" +
        pageSize +
        "&rolename=" +
        rolename;
    } else if (username == "" && rolename == "请选择角色") {
      url = "/baseUser/pageQuery?page=" + currentPage + "&pageSize=" + pageSize;
    } else {
      url =
        "/baseUser/pageQuery?page=" +
        currentPage +
        "&pageSize=" +
        pageSize +
        "&username=" +
        username +
        "&rolename=" +
        rolename;
    }
    // 发送请求
    getUserData(url);
  });

  // 添加-打开模态框
  $(".user-btn_one").click(() => {
    $(".modal-title").text("添加信息");
    // 清空文本框
   $('input[name=username]').val("");
   $('input[name=realname]').val("");
   $('input[name=password]').val("");
   $('input[type=radio]:checked').val("");
   $('input[name=telephone]').val("");
   $('input[name=birth]').val("");


    // 添加-添加用户信息
$(".btn-add").on("click",function(){
    // 获取用户输入的数据
    var username = $('input[name=username]').val();
    var realname = $('input[name=realname]').val();
    var password = $('input[name=password]').val();
    var gender = $('input[type=radio]:checked').val();
    var telephone = $('input[name=telephone]').val();
    var birth = $('input[name=birth]').val();//生日还没实现保存

    $.ajax({
      url:baseurl + '/baseUser/saveOrUpdate',
      type:"post",
      headers:{
      'Authorization':sessionStorage.getItem('token'),
      },
      data:{
          username:username,
          realname:realname,
          password:password,
          gender:gender,
          telephone:telephone,
          birth:birth,
      },
      success:function(res){
        console.log(res);
        $('#myModal').modal('hide');
        alert("保存成功！");
        getUserData(
    "/baseUser/pageQuery?page=" + currentPage + "&pageSize=" + pageSize
  );
      }
    })
})
  });


</script>
